import { defineStore } from 'pinia'
import { ref } from 'vue'
import { musicApi } from '@/api/music'

export const usePlayerStore = defineStore('player', () => {
  const currentSong = ref(null)
  const isPlaying = ref(false)
  const currentTime = ref(0)
  const duration = ref(0)
  const playlist = ref([])
  const currentIndex = ref(-1)
  const detailShow = ref(false)

  // 公共方法：获取歌曲完整信息（带URL和封面）
  const fetchSongInfo = async (song) => {
    const response = await musicApi.getSongUrl(song.songmid)
    let songUrl = ''

    if (typeof response.data === 'string') {
      songUrl = response.data
    } else if (response.data.url) {
      songUrl = response.data.url
    } else if (typeof response.data.data === 'string') {
      songUrl = response.data.data
    } else if (response.data.data && response.data.data.url) {
      songUrl = response.data.data.url
    }

    if (!songUrl) {
      throw new Error('歌曲URL为空')
    }

    if (!songUrl.startsWith('http')) {
      songUrl = `https://${songUrl}`
    }

    // 修改封面URL，使用本地代理
    const coverUrl = song.albummid
      ? `/music-photo/music/photo_new/T002R300x300M000${song.albummid}.jpg`
      : 'https://y.qq.com/mediastyle/global/img/album_300.png'

    return {
      ...song,
      url: songUrl,
      cover: coverUrl
    }
  }

  /**
   * 播放指定歌曲
   * @param {Object} song 歌曲对象
   */
  const playSong = async (song) => {
    try {
      console.log('调用 playSong，参数：', song)
      // 如果是同一首歌，只切换播放状态
      if (currentSong.value && currentSong.value.songmid === song.songmid) {
        console.log('同一首歌，切换播放状态')
        togglePlay()
        return true
      }
      // 记录当前播放状态，新歌曲默认播放
      isPlaying.value = true
      // 获取歌曲完整信息
      const songWithInfo = await fetchSongInfo(song)
      currentSong.value = songWithInfo
      // 更新播放列表
      const existingIndex = playlist.value.findIndex(item => item.songmid === song.songmid)
      if (existingIndex === -1) {
        playlist.value.push(song)
        currentIndex.value = playlist.value.length - 1
      } else {
        currentIndex.value = existingIndex
      }
      console.log('playSong 完成，当前歌曲：', currentSong.value, '当前索引：', currentIndex.value)
      return true
    } catch (error) {
      console.error('播放歌曲失败:', error)
      return false
    }
  }

  /**
   * 切换播放/暂停状态
   */
  const togglePlay = () => {
    isPlaying.value = !isPlaying.value
    console.log('togglePlay，当前 isPlaying：', isPlaying.value)
    // 如果没有当前歌曲且有播放列表，则播放第一首
    if (isPlaying.value && !currentSong.value && playlist.value.length > 0) {
      playSongByIndex(0)
    }
  }

  /**
   * 播放上一首
   */
  const playPrev = async () => {
    if (playlist.value.length <= 1) {
      console.log('播放列表不足，无法切换上一首')
      return
    }
    let prevIndex = currentIndex.value - 1
    if (prevIndex < 0) prevIndex = playlist.value.length - 1
    currentIndex.value = prevIndex
    console.log('切换到上一首，索引：', prevIndex)
    await playSongByIndex(prevIndex)
  }

  /**
   * 播放下一首
   */
  const playNext = async () => {
    if (playlist.value.length <= 1) {
      console.log('播放列表不足，无法切换下一首')
      return
    }
    let nextIndex = currentIndex.value + 1
    if (nextIndex >= playlist.value.length) nextIndex = 0
    currentIndex.value = nextIndex
    console.log('切换到下一首，索引：', nextIndex)
    await playSongByIndex(nextIndex)
  }

  /**
   * 根据索引播放歌曲
   * @param {number} index 歌曲索引
   */
  const playSongByIndex = async (index) => {
    if (index < 0 || index >= playlist.value.length) {
      console.log('索引越界，无法播放')
      return
    }
    const song = playlist.value[index]
    if (currentSong.value && currentSong.value.songmid === song.songmid) {
      console.log('当前已是该歌曲，无需切换')
      return true
    }
    const wasPlaying = isPlaying.value
    try {
      const songWithInfo = await fetchSongInfo(song)
      currentSong.value = songWithInfo
      const existingIndex = playlist.value.findIndex(item => item.songmid === song.songmid)
      if (existingIndex === -1) {
        playlist.value.push(song)
        currentIndex.value = playlist.value.length - 1
      } else {
        currentIndex.value = existingIndex
      }
      isPlaying.value = wasPlaying
      console.log('playSongByIndex 完成，当前歌曲：', currentSong.value, '当前索引：', currentIndex.value)
    } catch (error) {
      console.error('播放歌曲失败:', error)
    }
  }

  const addToPlaylist = (song) => {
    const existingIndex = playlist.value.findIndex(item => item.songmid === song.songmid)
    if (existingIndex === -1) {
      playlist.value.push(song)
    }

    if (!currentSong.value && playlist.value.length === 1) {
      currentIndex.value = 0
      playSongByIndex(0)
    }
  }

  const toggleDetailShow = () => {
    detailShow.value = !detailShow.value
  }

  const setDetailShow = (status) => {
    detailShow.value = status
  }

  return {
    currentSong,
    isPlaying,
    currentTime,
    duration,
    playlist,
    currentIndex,
    detailShow,
    playSong,
    togglePlay,
    playPrev,
    playNext,
    playSongByIndex,
    addToPlaylist,
    toggleDetailShow,
    setDetailShow
  }
})
